/*******************************************************************************
 * Copyright (c) 2000, 2022 IBM Corporation and others.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.gef.examples.logicdesigner.actions;

import java.util.List;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IWorkbenchPart;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;

import org.eclipse.gef.examples.logicdesigner.LogicMessages;
import org.eclipse.gef.examples.logicdesigner.LogicPlugin;
import org.eclipse.gef.examples.logicdesigner.model.LED;

public class IncrementDecrementAction extends org.eclipse.gef.ui.actions.SelectionAction {

	private static final String INCREMENT_REQUEST = "Increment"; //$NON-NLS-1$
	private static final String DECREMENT_REQUEST = "Decrement"; //$NON-NLS-1$

	public static final String INCREMENT = "Increment"; //$NON-NLS-1$
	public static final String DECREMENT = "Decrement"; //$NON-NLS-1$

	Request request;

	public IncrementDecrementAction(IWorkbenchPart part, boolean increment) {
		super(part);
		if (increment) {
			request = new Request(INCREMENT_REQUEST);
			setText(LogicMessages.IncrementDecrementAction_Increment_ActionLabelText);
			setId(INCREMENT);
			setToolTipText(LogicMessages.IncrementDecrementAction_Increment_ActionToolTipText);
			setImageDescriptor(ImageDescriptor.createFromFile(LogicPlugin.class, "icons/plus.gif")); //$NON-NLS-1$
		} else {
			request = new Request(DECREMENT_REQUEST);
			setText(LogicMessages.IncrementDecrementAction_Decrement_ActionLabelText);
			setId(DECREMENT);
			setToolTipText(LogicMessages.IncrementDecrementAction_Decrement_ActionToolTipText);
			setImageDescriptor(ImageDescriptor.createFromFile(LogicPlugin.class, "icons/minus.gif")); //$NON-NLS-1$
		}
		setHoverImageDescriptor(getImageDescriptor());
	}

	@Override
	protected boolean calculateEnabled() {
		return canPerformAction();
	}

	private boolean canPerformAction() {
		List<EditPart> selectedEditParts = getSelectedEditParts();
		if (selectedEditParts.isEmpty()) {
			return false;
		}
		return selectedEditParts.stream().allMatch(ep -> ep.getModel() instanceof LED);
	}

	private Command getCommand() {
		final CompoundCommand cc = new CompoundCommand();
		cc.setDebugLabel("Increment/Decrement LEDs");//$NON-NLS-1$
		getSelectedEditParts().stream().map(ep -> ep.getCommand(request)).forEach(cc::add);
		return cc;
	}

	@Override
	public void run() {
		execute(getCommand());
	}

}
